package com.example.Lezedata.ui.dataPage;

import androidx.lifecycle.ViewModelProvider;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.Lezedata.R;
import com.example.Lezedata.dataManager.GBUserManager;
import com.example.Lezedata.dataManager.LoginManager;
import com.example.Lezedata.net.GBError;
import com.example.Lezedata.net.GBNetRequest;
import com.example.Lezedata.net.ServerResponseObserver;
import com.example.Lezedata.ui.activity.person.PersonVc;
import com.example.Lezedata.ui.dataPage.subVc.ChequeList;
import com.example.Lezedata.ui.dataPage.subVc.DataNodeList;
import com.example.Lezedata.ui.fragment.BaseFragment;
import com.example.Lezedata.ui.fragment.commonfragment.AlertFragment;
import com.example.Lezedata.util.GBUtil;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;

import bid.Bid;
import common.Common;

public class DataPageFragment extends BaseFragment {

    private DataPageViewModel mViewModel;

    private TextView history;
    private LinearLayout dataView1;
    private LinearLayout dataView2;
    private LinearLayout dataView3;
    private LinearLayout dataView4;

    private TextView mynode;
    private TextView mytotal;
    public Bid.BeeVersion beeVersion;

    public static DataPageFragment newInstance() {
        return new DataPageFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.tab_data_page_fragment, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(DataPageViewModel.class);
        loadData();
        // TODO: Use the ViewModel
    }
    View layoutMynode;
    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        layoutMynode=findViewById(R.id.layout_mynode);
        layoutMynode.setVisibility(View.GONE);
        mynode = findViewWithTag("mynode");
        mytotal = findViewWithTag("mytotal");

        dataView1 = findViewWithTag("dataView1");
        dataView2 = findViewWithTag("dataView2");
        dataView3 = findViewWithTag("dataView3");
        dataView4 = findViewWithTag("dataView4");
        history = findViewWithTag("history");

        history.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(),DataNodeList.class);
                intent.putExtra("version",Bid.BeeVersion.BV_053.getNumber());
                baseVc().jumpActivityIntent(intent);
            }
        });

        findViewById(R.id.my_node).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(),DataNodeList.class);
                intent.putExtra("version",Bid.BeeVersion.BV_062.getNumber());
                baseVc().jumpActivityIntent(intent);
            }
        });

        findViewById(R.id.my_total).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                baseVc().jumpActivity(ChequeList.class);
            }
        });

        initData();
    }

    ArrayList<DataViewModel> models1 = new ArrayList<>();
    ArrayList<DataViewModel> models2 = new ArrayList<>();
    ArrayList<DataViewModel> models3 = new ArrayList<>();
    ArrayList<DataViewModel> models4 = new ArrayList<>();
    ArrayList<DataView> dataViews = new ArrayList<>();

    void initData(){
        models1.add(new DataViewModel("总节点数","0.0"));
        models1.add(new DataViewModel("活跃节点数","0.0"));
        models1.add(new DataViewModel("待部署节点数","0.0"));
        models1.add(new DataViewModel("节点活跃率","0.0"));

        models2.add(new DataViewModel("累计出票数","0.0"));
        models2.add(new DataViewModel("累计有效出票数","0.0"));
        models2.add(new DataViewModel("出票有效率","0.0"));
        models2.add(new DataViewModel("节点总连接数","0.0"));
        models2.add(new DataViewModel("总票面","0.0"));

        models3.add(new DataViewModel("预计收益","0.0"));
//        models3.add(new DataViewModel("我的总节点数","0.0"));
        models3.add(new DataViewModel("节点日均票面","0.0"));
        models3.add(new DataViewModel("节点最近到期日","0.0"));

        models4.add(new DataViewModel("我的收益比例","0.0"));
        models4.add(new DataViewModel("节点累计票面","0.0"));
        models4.add(new DataViewModel("激活节点数","0.0"));
//        models4.add(new DataViewModel("我的总出票数","0.0"));

        addViewToView(dataView1,models1);
        addViewToView(dataView2,models2);

        addViewToView(dataView3,models3);
        addViewToView(dataView4,models4);
    }

    void addViewToView(LinearLayout layout,ArrayList<DataViewModel> models){
        for (DataViewModel model:models) {
            DataView dataView = DataView.newInstance(getContext());
            dataView.setModel(model);
            layout.addView(dataView);
            dataViews.add(dataView);
        }
    }

    void loadData(){
        GBNetRequest.stubUser().getNodePoolProperty(Bid.GetNodePoolPropertyRequest.newBuilder().setBeeVersion(beeVersion).build(),
                ServerResponseObserver.observer(new ServerResponseObserver.requestListener<Bid.GetNodePoolPropertyResponse>() {
                    @Override
                    public void complete(final Bid.GetNodePoolPropertyResponse pool, GBError error) {
                        if (error == null){
                            GBNetRequest.stubUser().getUserNodeProfit(Bid.GetUserNodeProfitRequest.newBuilder().setBeeVersion(beeVersion).setUserId(GBUserManager.getUserId()).build(),
                                    ServerResponseObserver.observer(new ServerResponseObserver.requestListener<Bid.GetUserNodeProfitResponse>() {
                                        @Override
                                        public void complete(Bid.GetUserNodeProfitResponse value, GBError error) {
                                            if (error == null){
                                                refreshMyData(pool,value);
                                            }
                                        }
                                    })
                            );
                        }
                    }
                }));
    }


    @SuppressLint("DefaultLocale")
    void refreshMyData(Bid.GetNodePoolPropertyResponse pool, Bid.GetUserNodeProfitResponse value){

        history.setVisibility(value.getIsHave053()?View.VISIBLE:View.INVISIBLE);
        if (beeVersion == Bid.BeeVersion.BV_100){
            history.setVisibility(View.INVISIBLE);
        }
        models1.get(0).value = GBUtil.formatPrice(pool.getNodeCount(),false);
        models1.get(1).value = GBUtil.formatPrice(pool.getNodeCountActive(),false);
        models1.get(2).value = GBUtil.formatPrice(pool.getNodeCountPlan(),false);
        models1.get(3).value = pool.getNodeActivePercent();
        long chequeCount=0,chequeCountValid=0;
        chequeCount= pool.getChequeCount();
        chequeCountValid=   pool.getChequeCountValid();

        models2.get(0).value = GBUtil.formatPrice(chequeCount,false);
        models2.get(1).value = GBUtil.formatPrice(chequeCountValid,false);

        models2.get(2).value = pool.getChequeValidPercent();
        models2.get(3).value = GBUtil.formatPrice(pool.getPeerCount(),false);
        models2.get(4).value = GBUtil.formatPrice(pool.getPayout(),false);

//        String v1 = String.format("%.4f%%",((float)value.getPeerCount() * 100)/((float)pool.getPeerCount()));
//        String v2 = String.format("%.4f%%",((float)value.getChequeCount() * 100)/((float)pool.getChequeCount()));

        models3.get(0).value = "待空投结算";
        if (beeVersion == Bid.BeeVersion.BV_100){
            models3.get(0).value = GBUtil.formatPrice(value.getExpectProfit(),false);
        }
        //        models3.get(1).value = GBUtil.formatPrice(value.getNodeCount(),false);
        models3.get(1).value = value.getNodePoolProfitPeyday();
        if(value.getRecentExpireNode()>0) {
            models3.get(2).value = GBUtil.formatDateTime(value.getRecentExpireNode());
        }else{
            models3.get(2).value="无";
        }

        models4.get(0).value = value.getExpectProfitPercent();

        models4.get(1).value = value.getMyNodeProfitLastday();
        models4.get(2).value = String.valueOf(value.getNodeCountActive());
//        models4.get(3).value = GBUtil.formatPrice(value.getChequeCount(),false);

        mynode.setText(GBUtil.formatPrice(value.getNodeCount(),false));
        mytotal.setText(GBUtil.formatPrice(value.getChequeCount(),false));

        for (DataView dataView:dataViews){
            dataView.refresh();
        }

        if(value.getIsHave053()){
            show053Arent();
        }
        if(value.getNodeCount()>0){
            layoutMynode.setVisibility(View.VISIBLE);
        }else{

            showEmpty();
        }

    }


    void show053Arent(){
        AlertFragment fragment = new AlertFragment();
        fragment.text = "尊敬的客户：\n由于平台矿池节点已经从053节点全面升级到062节点，您将自动绑定新的062节点，同时会按照053的购买时间来保障用户的权益，053节点数据也将放到“053历史数据存档”中可供查看。";
        fragment.okListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        };
        fragment.show(getActivity().getSupportFragmentManager(),"alert");
    }
    void showEmpty(){
        AlertFragment fragment = new AlertFragment();
        fragment.text = "您当前未绑定任何结点，请联系您的市场推广人员安排绑定即可查看数据。";

        fragment.show(getActivity().getSupportFragmentManager(),"alert");

    }
}